import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_study/config/ConstString.dart';
import 'package:flutter_study/page/discovery_page.dart';
import 'package:flutter_study/page/home_page.dart';

import 'package:flutter_study/util/toast_util.dart';

class TabNavigation extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _TabNavigationState();
  }
}

class _TabNavigationState extends State<TabNavigation> {
  PageController _controller = new PageController(initialPage: 0);
  int _currentIndex = 0;
  DateTime lastTime;

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      child: Scaffold(
        body: PageView(
          controller: _controller,
          physics: NeverScrollableScrollPhysics(),
          children: [
            HomePage(),
            DiscoveryPage(),
          ],
        ),
        bottomNavigationBar: BottomNavigationBar(
          unselectedItemColor: Colors.grey,
          selectedItemColor: Colors.black87,
          currentIndex: _currentIndex,
          onTap: (index) {
            _controller.jumpToPage(index);
            setState(() {
              _currentIndex = index;
            });
          },
          type: BottomNavigationBarType.fixed,
          items: [
            _bottomItem(ConstString.daily_paper, 'images/ic_home_normal.png',
                'images/ic_home_selected.png', 0),
            _bottomItem(ConstString.discover, 'images/ic_discovery_normal.png',
                'images/ic_discovery_selected.png', 1),
          ],
        ),
      ),
      onWillPop: _onWillPop,
    );
  }

  _bottomItem(String title, String normalIcon, String selectIcon, int index) {
    return BottomNavigationBarItem(
        icon: Image.asset(normalIcon, width: 24, height: 24),
        activeIcon: Image.asset(selectIcon, width: 24, height: 24),
        label: title);
  }

  Future<bool> _onWillPop() async {
    if (lastTime == null ||
        DateTime.now().difference(lastTime) > Duration(seconds: 2)) {
      lastTime = DateTime.now();
      ToastUtil.showTip(ConstString.exit_tip);
      return false;
    } else {
      SystemNavigator.pop();
      return true;
    }
  }
}
